<template>
  <scroll-view scroll-y="true" class="my-exer">
    <view class="buttonContent">
      <view @click="toRestart" class="reload button">重置规则</view>
      <view class="info">
        <view class="qbNumContent">
          <view class="up item">
            <view class="title">单选: </view>
            <view class="num">{{ testInfo.radioNum }}</view>
          </view>
          <view class="item">
            <view class="title">多选: </view>
            <view class="num">{{ testInfo.multipleNum }}</view>
          </view>
        </view>
        <view class="qbNumContent">
          <view class="up item">
            <view class="title">判断: </view>
            <view class="num">{{ testInfo.determineNum }}</view>
          </view>
          <view class="item">
            <view class="title">总分: </view>
            <view class="num">{{ testInfo.totalScore }}</view>
          </view>
        </view>
      </view>
      <view @click="toExer" class="start button">开始考试</view>
    </view>
    <view class="buttonD"></view>
    <uni-list class="list_content">
      <view class="mockAllRu">
        <view class="card data_card testInfo">
          <view class="test_time"> 模拟考试 </view>
          <view class="test_card_status_info timeScore">
            <view class="time info timeInput">
              <text class="name">时长：</text>
              <uni-easyinput
                v-model="testInfo.testTime"
                type="number"
                @change="timeChange"
                placeholder="考试时间（分钟）"
              />
            </view>
            <view class="score info">
              <text class="name">及格：</text>
              <uni-easyinput
                v-model="testInfo.passScore"
                type="number"
                @blur="passScoreChange"
                placeholder="及格分数"
              />
              <text class="num"> &nbsp;&nbsp;/ {{ testInfo.totalScore }}</text>
            </view>
          </view>
          <view class="test_tip">
            注：单选每题一分，多选每题两分，判断每题一分。
          </view>
        </view>
      </view>
      <uni-collapse
        ref="collapse"
        v-model="collapseValue"
        @change="change"
        title-border="none"
        :border="false"
      >
        <uni-collapse-item
          :title="`${item.questionTypeName}(${
            item.totalScore ? item.totalScore : 0
          }分)`"
          class=""
          v-for="(item, index) in qbInfo.qbList"
          :key="item.id"
        >
          <template v-slot:title>
            <view class="rule_name">
              <text class="name">{{ item.questionTypeName }}</text>
              <text class="totalScore" style="color: #24b0fb"
                >({{ item.totalScore ? item.totalScore : 0 }}分)</text
              >
            </view>
          </template>
          <view class="content">
            <view class="data_card testInfo rules">
              <view class="test_card_status_info">
                <view class="rmContent">
                  <view class="time info ruleinputContent">
                    <text class="name">单选：</text>
                    <uni-easyinput
                      class="ruleInput"
                      v-model="item.radioNum"
                      type="number"
                      @blur="RuinputChange(item, index)"
                      :clearable="false"
                      placeholder="每题一分"
                    />
                    <text class="num">
                      可选：<text class="num1">
                        {{ item.radioAllMum }}
                      </text>
                    </text>
                  </view>
                  <view class="time info ruleinputContent">
                    <text class="name">多选：</text>
                    <uni-easyinput
                      class="ruleInput"
                      v-model="item.multipleNum"
                      type="number"
                      @blur="RuinputChange(item, index)"
                      :clearable="false"
                      placeholder="每题两分"
                    />
                    <text class="num">
                      可选：<text class="num1">
                        {{ item.multipleAllNum }}
                      </text></text
                    >
                  </view>
                </view>
                <view class="time info ruleinputContent">
                  <text class="name">判断：</text>
                  <uni-easyinput
                    class="ruleInput"
                    v-model="item.determineNum"
                    type="number"
                    @blur="RuinputChange(item, index)"
                    :clearable="false"
                    placeholder="每题一分"
                  />
                  <text class="num">
                    可选：<text class="num1">
                      {{ item.determineAllMum }}
                    </text></text
                  >
                </view>
              </view>
            </view>
          </view>
        </uni-collapse-item>
      </uni-collapse>
    </uni-list>
    <uni-load-more
      :status="listpage.status"
      :contentText="{
        contentdown: '点击查看更多',
        contentrefresh: '加载中',
        contentnomore: '到底了',
      }"
      @clickLoadMore="query(true)"
    ></uni-load-more>
    <view>
      <!-- 提示信息弹窗 -->
      <uni-popup ref="message" type="message">
        <uni-popup-message
          :type="msgType"
          :message="messageText"
          :duration="2000"
        ></uni-popup-message>
      </uni-popup>
    </view>
  </scroll-view>
</template>

<script lang="ts" setup>
import { reactive, ref } from "vue";
import { onLoad,onPullDownRefresh } from "@dcloudio/uni-app";
import { MyExer } from "@/ts";
import http from "@/utils/request";

// 定义变量

const qbContent = ref();
const msgType = ref("success"); // 提示信息类型

const messageText = ref(""); // 提示信息内容
const message = ref(null); // 提示信息内容
const collapseValue = ref([]);

const queryForm = reactive({
  // 查询表单
  name: "", // 名称
});
const listpage = reactive({
  // 分页列表
  curPage: 1,
  pageSize: 10,
  total: 0,
  list: [] as MyExer[],
  status: "more",
});
let qbForm = ref(null);
let testInfo = reactive({
  testTime: "60",
  passScore: "80",
  radioNum: 0,
  multipleNum: 0,
  determineNum: 0,

  totalScore: 0,
});

let qbInfo = reactive({
  qbList: [],
});

// 页面加载完毕，执行如下方法
onLoad(async () => {
  query(false);
  getDefaultMockRule();
});
const toRestart = () => {
  // 重置规则

  getDefaultMockRule();
};

const getDefaultMockRule = () => {
  http.post("myExamMock/defaultMockRule", {}).then((data) => {
    if (data.code == 200) {
      qbInfo.qbList = data.data; // 获取默认模拟考试规则
      testInfo.totalScore = 0;

      qbInfo.qbList.map((item) => {
        testInfo.totalScore += Number(item.totalScore);
      });
      getQbNum();
    } else {
      msgType.value = "error";
      messageText.value = "获取默认模拟考试规则失败";
      message.value.open();
    }
  });
};
// 统计单选、多选、判断的数量
const getQbNum = () => {
  let radioNum = 0;
  let multipleNum = 0;
  let determineNum = 0;
  qbInfo.qbList.map((item) => {
    radioNum += Number(item.radioNum);
    multipleNum += Number(item.multipleNum);
    determineNum += Number(item.determineNum);
  });
  testInfo.radioNum = radioNum;
  testInfo.multipleNum = multipleNum;
  testInfo.determineNum = determineNum;
};

// 校验输入的单选、多选、判断的数量是否超过题库中的数量
const RuinputChange = (qbData, index) => {
  if (qbData.radioNum > qbData.radioAllMum) {
    msgType.value = "error";
    messageText.value = "单选题超过题库数量";
    message.value.open();
    // 同时清空输入框
    qbInfo.qbList[index].radioNum = "";
  }
  console.log(index, "+++++");

  if (qbData.multipleNum > qbData.multipleAllNum) {
    msgType.value = "error";
    messageText.value = "多选题超过题库数量";
    message.value.open();
    // 同时清空输入框
    qbInfo.qbList[index].multipleNum = "";
    console.log(qbInfo.qbList, "+++++++++++++");
  }
  if (qbData.determineNum > qbData.determineAllMum) {
    msgType.value = "error";
    messageText.value = "判断题超过题库数量";
    message.value.open();
    // 同时清空输入框
    qbInfo.qbList[index].determineNum = "";
  }
  // 本题库计算总分
  qbInfo.qbList[index].totalScore =
    Number(qbData.radioNum) +
    Number(qbData.multipleNum) * 2 +
    Number(qbData.determineNum);

  // 所有题库总分
  testInfo.totalScore = 0; //先重置总分为0，避免之前的值影响结果
  qbInfo.qbList.map((item) => {
    testInfo.totalScore += Number(item.totalScore);
  });
  getQbNum();
};
// 及格分数改变
const passScoreChange = () => {
  let scoreStr = testInfo.passScore.toString();
  if (scoreStr[0] === "0" && scoreStr.length > 1) {
    msgType.value = "error";
    messageText.value = "分数输入错误，不能以0开头的数字";
    message.value.open();
    // 同时清空输入框
    testInfo.passScore = "";
  } else if (testInfo.passScore > testInfo.totalScore) {
    msgType.value = "error";
    messageText.value = "及格分数超过总分数";
    message.value.open();
    // 同时清空输入框
    testInfo.passScore = "";
  }
};

// 考试时间改变
const timeChange = () => {
  let timeStr = testInfo.testTime.toString();
  if (timeStr[0] === "0" && timeStr.length > 1) {
    msgType.value = "error";
    messageText.value = "时间输入错误，不能以0开头的数字";
    message.value.open();
    // 同时清空输入框
    testInfo.testTime = "";
  } else if (testInfo.testTime == 0) {
    msgType.value = "error";
    messageText.value = "考试时间不能为0";
    message.value.open();
    // 同时清空输入框
    testInfo.testTime = "";
  }
};

/**
 * 查询
 *
 * @param append 追加数据
 */
async function query(append: boolean) {
  listpage.status = "loading";
  if (append) {
    listpage.curPage++;
  } else {
    listpage.curPage = 1;
  }

  const { code, data } = await http.post("myExer/listpage", {
    ...queryForm,
    curPage: listpage.curPage,
    pageSize: listpage.pageSize,
  });

  if (code !== 200) {
    return;
  }

  listpage.total = data.total;

  if (append) {
    if (data.list.length) {
      listpage.list.push(...data.list);
    }
  } else {
    listpage.list = data.list;
  }

  // 将列表中的examStartTime 最后两位秒去掉
  listpage.list.map((item) => {
    item.startTime = item.startTime.substring(0, item.startTime.length - 3);
    item.endTime = item.endTime.substring(0, item.endTime.length - 3);
  }); // 去掉最后两位秒

  if (listpage.list.length < listpage.total) {
    listpage.status = "more";
  } else {
    listpage.status = "no-more";
  }
}

// 去练习页面 提交模拟考试规则，按照单选在前，多选在后，判断在最后的顺序排列

async function toExer(exer: MyExer) {
  // 先判断用户是否填考试时长
  if (testInfo.testTime == 0) {
    msgType.value = "error";
    messageText.value = "请填写考试时长";
    message.value.open();
    return;
  }
  //判断用户是否填考试时长
  if (testInfo.passScore == 0) {
    msgType.value = "error";
    messageText.value = "请填写及格分数";
    message.value.open();
    return;
  } else if (testInfo.passScore > testInfo.totalScore) {
    msgType.value = "error";
    messageText.value = "及格分数超过总分数";
    message.value.open();
    return;
  }

  const resendData = {
    passScore: testInfo.passScore,
    passTime: testInfo.testTime,
    totalScore: testInfo.totalScore,
    examRules: makeSendData(),
  };
  uni.showLoading({
    title: "生成试卷中...",
  });

  try {
    const { code, data } = await http.post("myExamMock/publish", resendData, {
      contentType: "json",
    });

    const publishData = data;

    if (code == 200) {
      const barData = await http.post("progressBar/get", { id: publishData });
      console.log(barData, "barData");

      if (barData.code == 200) {
        const examUnStartList = await http.post("myExamMock/examUnStart");
        if (examUnStartList.code == 200 && examUnStartList.data?.id) {
          uni.navigateTo({
            url: `/pages/myMock/myMockPage?exerId=${examUnStartList.data.id}`,
          });
        } else {
          navigateToExam();
        }
      }
    }
  } catch (exception) {
    console.error(exception);
  } finally {
    uni.hideLoading(); // 取消加载
  }
}
async function navigateToExam() {
  let timer = setInterval(async function () {
    try {
      const examUnStartList = await http.post("myExamMock/examUnStart");
      if (examUnStartList.code == 200 && examUnStartList.data?.id) {
        uni.navigateTo({
          url: `/pages/myMock/myMockPage?exerId=${examUnStartList.data.id}`,
        });
        clearInterval(timer);
      }
    } catch (error) {
      console.error(error);
    }
  }, 1000);
}
const makeSendData = () => {
  let radioArr: any[] = [];
  let multipleArr: any[] = [];
  let determineArr: any[] = [];

  qbInfo.qbList.forEach((element) => {
    ["radioNum", "multipleNum", "determineNum"].forEach((key) => {
      if (element[key] > 0) {
        let examRule = {
          score: key === "multipleNum" ? 2 : 1,
          scores: key === "multipleNum" ? [1] : [],
          num: element[key],
          type: 2,
          questionTypeId: element.questionTypeId,
          questionType: key === "radioNum" ? 1 : key === "multipleNum" ? 2 : 4,
        };
        switch (key) {
          case "radioNum":
            radioArr.push(examRule);
            break;
          case "multipleNum":
            multipleArr.push(examRule);
            break;
          case "determineNum":
            determineArr.push(examRule);
            break;
          default:
            break;
        }
      }
    });
  });

  let examRules = [...radioArr, ...multipleArr, ...determineArr]; // 按照单选，多选，判断的顺序拼接数组

  // 更新 no 字段值
  examRules.forEach((rule, index) => {
    rule.no = index + 1;
  });

  return examRules;
};
</script>

<style lang="scss" scoped>
.my-exer {
  height: 100%;
}
.buttonContent {
  height: 160rpx;
  position: fixed;
  top: -24rpx;
  width: 100%;
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 100rpx;
  z-index: 10;
  background: #fff;
  box-shadow: 0 0 20rpx 0 rgba(0, 0, 0, 0.1);
  .info {
    display: flex;
    width: 40%;
    flex-direction: column;
    align-items: center;
    margin-left: 40rpx;
    .qbNumContent {
      display: flex;
      height: 50rpx;
      width: 90%;
      justify-content: flex-start;
      .item {
        display: flex;
      }
      .up {
        margin-right: 20rpx;
      }
      .title {
        color: #5ba585;
      }
    }
  }
  .button {
    width: 160rpx;
    height: 80rpx;
    line-height: 80rpx;
    text-align: center;
    border-radius: 34rpx;
  }
  .start {
    margin-right: 20rpx;
    background-color: #5ba585;
    background: linear-gradient(to right, #24b0fb, #f58177);
    box-shadow: 0 0 20rpx 0 rgba(0, 0, 0, 0.1);
    color: #fff;
  }
  .reload {
    margin-left: 20rpx;
    background: linear-gradient(to right, #339bfb, #5caffc);
    box-shadow: 0 0 20rpx 0 rgba(0, 0, 0, 0.1);
    color: #fff;
  }
}
.buttonD {
  height: 160rpx;
}
.rulesForm {
  width: 500rpx;
  margin-left: 6rpx;
  margin-right: 20rpx;
  margin-top: 20rpx;
}
/* 固定高度，超出滚动*/

.list_content {
}
/* 卡片圆角 阴影效果*/
.card {
  margin-bottom: 20rpx;
  margin-top: 20rpx;
  background-color: #fff;
  border-radius: 20rpx;
  box-shadow: 0 0 20rpx 0 rgba(0, 0, 0, 0.1);
}
.testInfo {
  height: 240rpx;
  .test_card_status_info {
    height: 210rpx;
    margin: 6rpx;
    margin-left: 20rpx;
    padding-right: 10rpx;
    .ruleInput {
      margin-right: 20rpx;
    }
    .rmContent {
    }
  }
  .timeScore {
    height: 100rpx;
    display: flex;
    justify-content: center;
    margin-left: 8rpx;
  }
  .test_tip {
    margin-left: 20rpx;
    font-size: 24rpx;
    color: #999;
  }
  .test_time {
    color: #339bfb;
  }

  .info {
    display: flex;
    align-items: center;
  }
  .time {
    height: 100rpx;
    width: 87%;
  }
  .timeInput {
    width: 53%;
    margin-right: 20rpx;
  }
  .score {
    height: 100rpx;
    width: 70%;
  }
}
.rules {
  height: 300rpx;

  .ruleinputContent {
    margin-left: 40rpx;
    font-size: 28rpx;
    .num {
      width: 140rpx;
    }
    .num1 {
      color: #ce6872;
    }
  }
}
.rule_name {
  display: flex;
  height: 90rpx;
  justify-content: flex-start;
  align-items: center;
  font-size: 30rpx;
  margin-left: 20rpx;
  .name {
    font-weight: bold;
  }
}
.mockAllRu {
  display: flex;
  justify-content: center;
  .data_card {
    width: 90%;
  }
  .qbData {
    height: 260rpx;
  }
  .button_card {
    width: 16%;
    margin-top: 20rpx;
    margin-left: 10rpx;
    display: flex;
    flex-direction: column;
    align-items: center;
    .edit_button {
      background: #339bfb;
    }
    .delete_button {
      background: #24b0fb;
      margin-top: 10rpx;
    }
    .button_content {
      width: 100%;
      height: 60rpx;
      display: flex;
      justify-content: center;
      align-items: center;
      color: #fff;
      font-size: 22rpx;
      border-radius: 20rpx;
      box-shadow: 0 0 20rpx 0 rgba(0, 0, 0, 0.1);
    }
  }
  .all_btn {
    margin-top: 38rpx;
    .button_content {
      height: 100rpx;
      font-size: 28rpx;
    }
  }
}

.test_time {
  height: 60rpx;
  margin: 6rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}
.test_card_status {
  height: 160rpx;
  margin: 6rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}
</style>
